# -*- coding: utf-8 -*-


import requests
import re
from models import Message, DBManager
from PySide2.QtCore import QObject, Signal, Slot
class Service():
    class MySignal(QObject):
        new_message = Signal()
        
    mySignal = MySignal()    
    session = requests.Session()
    login_url = "http://139.196.18.36/edoas2/member.jsp"
    login_data = {"username":"wangjiangyixiao","pword":"wjyx5693"}
    msg_url = "http://139.196.18.36/edoas2/shiwuchuli/getallreceivedmsg"
    db = DBManager("db.sqlite3")
    isLogin = False
    def __init__(self):
        login_ret = self.session.post(url=self.login_url,data=self.login_data)
        if "index" in login_ret.text:
            self.isLogin = True

    def readMessage(self,msg):
        if self.db.getMessage(msg.id) != None:
            msg.content = self.db.getMessage(msg.id)
            return msg
        msg_url_content ="http://139.196.18.36/edoas2/shiwuchuli/%s" % msg.url
        content = self.session.get(msg_url_content)

        pat = re.finditer(r'<strong>发送人：</strong>.*?</p>([\s\S]*?)<table.*?>([\s\S]*?)</table>',content.text,re.M|re.I)
        for i in pat:
            msg.content = i.group().replace("/edoas2/include/upload/showaccessory","http://139.196.18.36/edoas2/include/upload/showaccessory")
            print(msg.content)
        self.db.addMessage(msg)
        return msg

    def Pull(self):
        _list = []
        if self.isLogin:
            msg_ret = self.session.get(self.msg_url)
            it = re.finditer(r'(openthemsg\?id=(\d+?)&type=shoujian)\'>(.*?)<[\s\S]*?#D4D0C8;\' >(.*?)&nbsp;</td>[\s\S]*?#D4D0C8;\' >(.*?)&nbsp;</td>[\s\S]*?#D4D0C8;\' >(.*?)&nbsp;</td>',msg_ret.text,re.M|re.I)
            for i in it:
                msg=Message(id = i.group(2),title = i.group(3),date = i.group(6),url=i.group(1),sector=i.group(4),counterpart=i.group(5))
                _list.append(msg)
            self.mySignal.new_message.emit()
        return _list
    
    def Show(self,filter='all',limit=10):
        _list = self.db.getAllMessage(filter,limit)
        for i in _list:
            print(i)

    def GetAll(self,filter='all',limit=10):
        _list = self.db.getAllMessage(filter,limit)
        return _list
svr = Service()